package com.ruoyi.app.common

import cn.hutool.core.io.FileUtil
import cn.hutool.core.util.RandomUtil
import cn.hutool.core.util.StrUtil
import cn.hutool.core.util.URLUtil
import com.aliyun.com.viapi.FileUtils
import com.ruoyi.oss.client.IOSSClient
import com.ruoyi.oss.client.OSSClientFactory
import com.ruoyi.oss.config.OssConfig
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.net.URL

@Service
class NetUrlUploadOss {

    @Autowired
    private lateinit var ossConfig: OssConfig


    fun upload(url: String): String {

        val ossClient: IOSSClient = OSSClientFactory.build("aliyun")
        ossClient.init(ossConfig)
        FileUtil.getSuffix(url)
        return ossClient.upload(URLUtil.getStream(URL(url)), "${RandomUtil.randomNumbers(6)}.${FileUtil.getSuffix(url)?.run { split("?")[0] }
            ?: throw Exception("请上传符合规定的图片或者视频格式!")}")
    }

    fun upload(url: String, suffix: String): String {

        val ossClient: IOSSClient = OSSClientFactory.build("aliyun")
        ossClient.init(ossConfig)
        return ossClient.upload(URLUtil.getStream(URL(url)), "${RandomUtil.randomNumbers(6)}.$suffix")
    }
}

fun String.trans(): String {
    val accessKey = "LTAI5tRQ1acQfyPAnkCWvMAd" //您的AccessKeyID
    val accessKeySecret = "SVVk0Non9jDhpSdISorUnfYZFBqs9c" //您的AccessKeySecret
    val fileUtils: FileUtils = FileUtils.getInstance(accessKey, accessKeySecret)
    return this.takeIf { it.isNotBlank() }?.run { fileUtils.upload(StrUtil.trim(this)) } ?: ""
}